<template>
  <div class="post-loan-warning">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷后预警</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddRule">新增预警规则</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="预警等级">
          <el-select v-model="searchForm.level" placeholder="请选择预警等级" clearable>
            <el-option label="一级预警" value="level1"></el-option>
            <el-option label="二级预警" value="level2"></el-option>
            <el-option label="三级预警" value="level3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="未处理" value="pending"></el-option>
            <el-option label="处理中" value="processing"></el-option>
            <el-option label="已处理" value="completed"></el-option>
            <el-option label="已关闭" value="closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 预警规则表格 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="预警规则" name="rules">
          <el-table :data="rulesData" border style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="规则名称" width="180"></el-table-column>
            <el-table-column prop="type" label="规则类型" width="120">
              <template #default="scope">
                {{ getRuleType(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="level" label="预警等级" width="100">
              <template #default="scope">
                <el-tag :type="getWarningLevelType(scope.row.level)">{{ getWarningLevelText(scope.row.level) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="threshold" label="阈值" width="120"></el-table-column>
            <el-table-column prop="description" label="规则描述"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="'active'"
                  :inactive-value="'inactive'"
                  @change="handleRuleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="handleEditRule(scope.row)">编辑</el-button>
                <el-button link type="primary" @click="handleDeleteRule(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 预警记录表格 -->
        <el-tab-pane label="预警记录" name="records">
          <el-table :data="recordsData" border style="width: 100%" v-loading="loading">
            <el-table-column prop="loanNo" label="贷款编号" width="180"></el-table-column>
            <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
            <el-table-column prop="ruleName" label="预警规则" width="180"></el-table-column>
            <el-table-column prop="warningTime" label="预警时间" width="180"></el-table-column>
            <el-table-column prop="level" label="预警等级" width="100">
              <template #default="scope">
                <el-tag :type="getWarningLevelType(scope.row.level)">{{ getWarningLevelText(scope.row.level) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="预警描述"></el-table-column>
            <el-table-column prop="status" label="处理状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="handleProcess(scope.row)" :disabled="scope.row.status === 'completed' || scope.row.status === 'closed'">处理</el-button>
                <el-button link type="primary" @click="handleViewRecord(scope.row)">查看</el-button>
                <el-button link type="primary" @click="handleClose(scope.row)" :disabled="scope.row.status === 'closed'">关闭</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑预警规则对话框 -->
    <el-dialog 
      v-model="ruleDialogVisible" 
      :title="ruleForm.id ? '编辑预警规则' : '新增预警规则'"
      width="600px"
    >
      <el-form :model="ruleForm" label-width="100px" :rules="ruleRules" ref="ruleFormRef">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称"></el-input>
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择规则类型" style="width: 100%">
            <el-option label="逾期预警" value="overdue"></el-option>
            <el-option label="还款预警" value="repayment"></el-option>
            <el-option label="担保预警" value="guarantee"></el-option>
            <el-option label="财务预警" value="financial"></el-option>
            <el-option label="经营预警" value="business"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警等级" prop="level">
          <el-select v-model="ruleForm.level" placeholder="请选择预警等级" style="width: 100%">
            <el-option label="一级预警" value="level1"></el-option>
            <el-option label="二级预警" value="level2"></el-option>
            <el-option label="三级预警" value="level3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值" prop="threshold">
          <el-input v-model="ruleForm.threshold" placeholder="请输入阈值">
            <template #append>{{ getThresholdUnit(ruleForm.type) }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" rows="3" placeholder="请输入规则描述"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="ruleForm.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRule">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预警处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="预警处理" width="600px">
      <el-form :model="processForm" label-width="100px" :rules="processRules" ref="processFormRef">
        <el-form-item label="处理方式" prop="method">
          <el-select v-model="processForm.method" placeholder="请选择处理方式" style="width: 100%">
            <el-option label="电话沟通" value="phone"></el-option>
            <el-option label="现场走访" value="visit"></el-option>
            <el-option label="书面通知" value="notice"></el-option>
            <el-option label="其他方式" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理人员" prop="processor">
          <el-select v-model="processForm.processor" placeholder="请选择处理人员" style="width: 100%">
            <el-option
              v-for="item in processorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果" prop="result">
          <el-input v-model="processForm.result" type="textarea" rows="3" placeholder="请输入处理结果"></el-input>
        </el-form-item>
        <el-form-item label="跟进措施" prop="followUp">
          <el-input v-model="processForm.followUp" type="textarea" rows="3" placeholder="请输入跟进措施"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看预警记录对话框 -->
    <el-dialog v-model="viewDialogVisible" title="预警记录详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentRecord.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentRecord.customerName }}</el-descriptions-item>
        <el-descriptions-item label="预警规则">{{ currentRecord.ruleName }}</el-descriptions-item>
        <el-descriptions-item label="预警时间">{{ currentRecord.warningTime }}</el-descriptions-item>
        <el-descriptions-item label="预警等级">
          <el-tag :type="getWarningLevelType(currentRecord.level)">{{ getWarningLevelText(currentRecord.level) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusType(currentRecord.status)">{{ getStatusText(currentRecord.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预警描述" :span="2">{{ currentRecord.description }}</el-descriptions-item>
      </el-descriptions>

      <div v-if="currentRecord.processRecords && currentRecord.processRecords.length">
        <el-divider>处理记录</el-divider>
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in currentRecord.processRecords"
            :key="index"
            :timestamp="record.processTime"
            :type="getTimelineItemType(record.status)"
          >
            <h4>{{ getProcessMethodText(record.method) }}</h4>
            <p>处理人：{{ record.processor }}</p>
            <p>处理结果：{{ record.result }}</p>
            <p>跟进措施：{{ record.followUp }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postloanWarningApi } from '@/api/postloan'

// 表格数据
const loading = ref(false)
const activeTab = ref('rules')
const rulesData = ref([])
const recordsData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  level: '',
  status: '',
  warningType: '',
  dateRange: []
})

// 预警规则表单
const ruleDialogVisible = ref(false)
const ruleFormRef = ref(null)
const ruleForm = reactive({
  id: '',
  name: '',
  type: '',
  level: '',
  threshold: '',
  description: '',
  status: 'active'
})

// 规则表单校验规则
const ruleRules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择预警等级', trigger: 'change' }],
  threshold: [{ required: true, message: '请输入阈值', trigger: 'blur' }],
  description: [{ required: true, message: '请输入规则描述', trigger: 'blur' }]
}

// 预警处理表单
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  method: '',
  processor: '',
  result: '',
  followUp: ''
})

// 处理表单校验规则
const processRules = {
  method: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  processor: [{ required: true, message: '请选择处理人员', trigger: 'change' }],
  result: [{ required: true, message: '请输入处理结果', trigger: 'blur' }],
  followUp: [{ required: true, message: '请输入跟进措施', trigger: 'blur' }]
}

// 处理人员选项
const processorOptions = ref([])

// 查看对话框
const viewDialogVisible = ref(false)
const currentRecord = ref({})

// 获取规则类型文本
const getRuleType = (type) => {
  const types = {
    overdue: '逾期预警',
    repayment: '还款预警',
    guarantee: '担保预警',
    financial: '财务预警',
    business: '经营预警'
  }
  return types[type] || '未知'
}

// 获取阈值单位
const getThresholdUnit = (type) => {
  const units = {
    overdue: '天',
    repayment: '%',
    guarantee: '%',
    financial: '%',
    business: '%'
  }
  return units[type] || ''
}

// 获取预警等级类型
const getWarningLevelType = (level) => {
  const types = {
    level1: 'success',
    level2: 'warning',
    level3: 'danger'
  }
  return types[level] || 'info'
}

// 获取预警等级文本
const getWarningLevelText = (level) => {
  const texts = {
    level1: '一级预警',
    level2: '二级预警',
    level3: '三级预警'
  }
  return texts[level] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'danger',
    processing: 'warning',
    completed: 'success',
    closed: 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '未处理',
    processing: '处理中',
    completed: '已处理',
    closed: '已关闭'
  }
  return texts[status] || '未知'
}

// 获取处理方式文本
const getProcessMethodText = (method) => {
  const texts = {
    phone: '电话沟通',
    visit: '现场走访',
    notice: '书面通知',
    other: '其他方式'
  }
  return texts[method] || '未知'
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const types = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return types[status] || 'info'
}

// 标签页切换
const handleTabClick = () => {
  fetchData()
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      loanNo: searchForm.loanNo,
      customerName: searchForm.customerName,
      level: searchForm.level,
      status: searchForm.status,
      warningType: searchForm.warningType,
      startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
      endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : ''
    }
    
    const res = await postloanWarningApi.getList(params)
    if (activeTab.value === 'rules') {
      rulesData.value = res.data.rows
    } else {
      recordsData.value = res.data.rows
    }
    total.value = res.data.total
    loading.value = false
  } catch (error) {
    console.error('获取数据失败:', error)
    loading.value = false
  }
}

// 获取处理人员选项
const fetchProcessorOptions = () => {
  postloanWarningApi.getProcessorOptions().then(res => {
    processorOptions.value = res.data
  })
}

// 新增预警规则
const handleAddRule = () => {
  ruleForm.id = ''
  ruleForm.name = ''
  ruleForm.type = ''
  ruleForm.level = ''
  ruleForm.threshold = ''
  ruleForm.description = ''
  ruleForm.status = 'active'
  
  ruleDialogVisible.value = true
}

// 编辑预警规则
const handleEditRule = (row) => {
  Object.assign(ruleForm, row)
  ruleDialogVisible.value = true
}

// 提交预警规则
const submitRule = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    if (ruleForm.id) {
      await postloanWarningApi.updateRule(ruleForm)
      ElMessage.success('编辑成功')
    } else {
      await postloanWarningApi.addRule(ruleForm)
      ElMessage.success('新增成功')
    }
    ruleDialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('表单校验失败:', error)
  }
}

// 删除预警规则
const handleDeleteRule = (row) => {
  ElMessageBox.confirm(`确认删除该预警规则吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    postloanWarningApi.deleteRule(row.id).then(() => {
      ElMessage.success('删除成功')
      fetchData()
    })
  }).catch(() => {})
}

// 规则状态变更
const handleRuleStatusChange = (row) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  postloanWarningApi.updateRuleStatus(row.id, newStatus).then(() => {
    ElMessage.success(`规则状态已${newStatus === 'active' ? '启用' : '停用'}`)
    fetchData()
  })
}

// 处理预警
const handleProcess = (row) => {
  processForm.id = row.id
  processForm.method = ''
  processForm.processor = ''
  processForm.result = ''
  processForm.followUp = ''
  
  processDialogVisible.value = true
  fetchProcessorOptions()
}

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    await postloanWarningApi.handleWarning(processForm)
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('表单校验失败:', error)
  }
}

// 查看预警记录
const handleViewRecord = (row) => {
  loading.value = true
  postloanWarningApi.getDetail(row.id).then(res => {
    currentRecord.value = res.data
    viewDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 关闭预警
const handleClose = (row) => {
  ElMessageBox.confirm(`确认关闭该预警记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    postloanWarningApi.closeWarning(row.id).then(() => {
      ElMessage.success('关闭成功')
      fetchData()
    })
  }).catch(() => {})
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.post-loan-warning {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 